package com.hp.service.impl;

import com.alibaba.fastjson.JSON;
import com.hp.client.LarkRobotClient;
import com.hp.config.properties.LarkRobotProperties;
import com.hp.entity.request.AlarmContentRequest;
import com.hp.entity.request.LarkMessageRequest;
import com.hp.entity.request.content.PostContent;
import com.hp.entity.response.MessageResponse;
import com.hp.enums.MessageTypeEnum;
import com.hp.service.SendMessageService;
import com.hp.utils.LarkRobotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author hp
 */
@Slf4j
@Service
public class SendMessageServiceImpl implements SendMessageService {

    @Resource
    private LarkRobotClient larkRobotClient;

    @Resource
    private LarkRobotProperties larkRobotProperties;

    @Override
    public MessageResponse sendMessage(AlarmContentRequest request) {
        if (!larkRobotProperties.getEnabled()) {
            MessageResponse messageResponse = new MessageResponse();
            messageResponse.setCode(-1).setMessage("Lark Robot config is not enabled");
            log.info("排课状态字段更新失败，发送lark结果： {}", JSON.toJSON(messageResponse));
            return messageResponse;
        }

        // 生成时间戳和签名
        int timestamp = (int) (System.currentTimeMillis() / 1000);
        String sign;
        try {
            sign = LarkRobotUtils.genSign(larkRobotProperties.getSecret(), timestamp);
        } catch (Exception e) {
            log.error("加密失败: {}", e.getMessage(), e);
            throw new RuntimeException("加密失败");
        }
        // 构造消息内容
        PostContent postContent = LarkRobotUtils.getPostContent(request);
        // 构造消息请求对象
        String requestJson = this.getRequestJson(timestamp, sign, postContent);
        // 使用 Feign 调用接口
        String response;
        try {
            response = larkRobotClient.sendMessage(requestJson);
        } catch (Exception e) {
            log.error("发送lark异常: {}", e.getMessage(), e);
            throw e;
        }
        MessageResponse messageResponse = JSON.parseObject(response, MessageResponse.class);
        log.info("发送lark结果: {}", messageResponse);
        return messageResponse;
    }

    @Override
    @Async("asyncCommonExecutor")
    public void sendMessageAsync(AlarmContentRequest request) {
        sendMessage(request);
    }


    private String getRequestJson(int timestamp, String sign, PostContent postContent) {
        LarkMessageRequest larkMessageRequest = new LarkMessageRequest();
        larkMessageRequest.setTimestamp(timestamp);
        larkMessageRequest.setSign(sign);
        larkMessageRequest.setMsgType(MessageTypeEnum.POST.getType());
        larkMessageRequest.setContent(postContent);
        return JSON.toJSONString(larkMessageRequest);
    }
}
